import axios from 'axios'
export default {
  // 开启命名空间
  namespaced: true,
  state () {
    return {
      list: []
    }
  },
  mutations: {
    updateList (state, list) {
      state.list = list
    },
    updateCount (state, obj) {
      const goods = state.list.find(item => item.id === obj.id)
      goods.count = obj.count
    }
  },
  actions: {
    async getListAction (context) {
      const res = await axios.get('http://localhost:3000/cart')
      context.commit('updateList', res.data)
    },
    async updateCountAction (context, obj) {
      // 1.1 调用更新商品数量的接口
      const res = await axios.patch(`http://localhost:3000/cart/${obj.id}`, { count: obj.count })
      console.log(res)

      // 1.2 提交mutations
      context.commit('updateCount', obj)
    }
  },
  getters: {
    // 1. 计算商品的总数量
    total (state) {
      return state.list.reduce((sum, item) => sum + item.count, 0)
    },

    // 2. 计算商品的总价格
    totalPrice (state) {
      return state.list.reduce((sum, item) => sum + item.count * item.price, 0)
    }
  }
}
